package com.zy.design.pattern.proxy.rpc.client;

import com.zy.design.pattern.proxy.rpc.RPCMeat;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.SneakyThrows;

import java.io.*;
import java.net.Socket;

/**
 * @author zhaoyi
 * @date 2021/4/8 17:23
 */
@Data
@AllArgsConstructor
public class ClientInstance {
    private String address;
    private int port;


    @SneakyThrows
    public Object sendRPC(RPCMeat rpcMeat) {
        OutputStream outputStream = null;
        ObjectOutputStream objectOutputStream = null;
        InputStream inputStream = null;
        ObjectInputStream objectInputStream = null;

        try {
            Socket socket = new Socket(address, port);
            outputStream = socket.getOutputStream();
            objectOutputStream = new ObjectOutputStream(outputStream);
            objectOutputStream.writeObject(rpcMeat);

            inputStream = socket.getInputStream();
            objectInputStream = new ObjectInputStream(inputStream);
            return objectInputStream.readObject();


        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }finally {
            if (outputStream != null){
                outputStream.close();
            }
            if (objectOutputStream != null){
                objectOutputStream.close();
            }
            if (inputStream != null){
                inputStream.close();
            }
            if (objectInputStream != null){
                objectInputStream.close();
            }
        }


        return null;
    }
}
